﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TS2015.Models;
using Kendo.Mvc.UI;
using Kendo.Mvc.Extensions;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Text;
using System.Data.OleDb;
using System.Data;

namespace TS2015.Areas.Admin.Controllers
{
    public class CandidateManagementController : Controller
    {
        TS2015Context db = new TS2015Context();
        // GET: Admin/CandidateManagement
        bool CheckHighSchool10, CheckHighSchool11, CheckHighSchool12, CheckProvince, CheckCandidate, CheckCommune;
        string Province;
        int idtruong10, idtruong11, idtruong12;
        int No = 0;
        List<SelectListItem> mess = new List<SelectListItem>();
        #region// Check int, float, datetime
        //bool CheckDateTime(string String)
        //{
        //    if (DateTime.TryParse(String, out Date))
        //    {
        //        return true;
        //    }
        //    else
        //    {
        //        return false;
        //    }
        //}
        bool CheckInt(string String)
        {
            int Int;
            if (Int32.TryParse(String, out Int))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        bool CheckFloat(string String)
        {
            float Float;
            if (float.TryParse(String, out Float))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion      
        public JsonResult GetMajorByPhylum(int manganh)
        {
            var major = from c in db.TbChuyenNganhs
                        where c.IDNganh == manganh
                        select c;
            return Json(new SelectList(major.ToList(), "MaChuyenNganh", "TenChuyenNganh"), JsonRequestBehavior.AllowGet);
        }
        public ActionResult CandidateList()
        {
            Session["current_url"] = Request.Url.AbsoluteUri;
            if (!CheckRole.IsRole("candidate", Session["Function"] as string[]))
                return Content("Bạn chưa <a href='/Admin/Home/Login'>đăng nhập hệ thống</a> hoặc không có quyền sử dụng chức năng này.");

            if (!Request.IsAjaxRequest())
                return View();

            return PartialView();
        }
        public ActionResult CapNhatDiem(string id)
        {
            TbThiSinh data = null;

            if (id == "")
            {
                ModelState.AddModelError("Error", "Mã thí sinh không đúng");                
            }
            else
            {
                data = db.TbThiSinhs.Include(e => e.TbDiemTotNghieps).Where(e => e.MaTS == id).FirstOrDefault();
                ViewBag.TbDiemTotNghiep = db.TbDiemTotNghieps.Include(e => e.TbMonTotNghiep).Where(e=>e.MaTS==id);
            }

            if (!Request.IsAjaxRequest())
                return View(data);

            return PartialView(data);
        }

        public ActionResult QuanLyDiem()
        {
            Session["current_url"] = Request.Url.AbsoluteUri;
            //if (!CheckRole.IsRole("candidate", Session["Function"] as string[]))
            //    return Content("Bạn chưa <a href='/Admin/Home/Login'>đăng nhập hệ thống</a> hoặc không có quyền sử dụng chức năng này.");           

            if (!Request.IsAjaxRequest())
                return View();

            return PartialView();
        }
        
        public ActionResult GetCandidate()
        {
            var CandidateList = from a in db.TbThiSinhs
                                join b in db.TbDanTocs on a.MaDanToc equals b.MaDanToc
                                join c in db.TbThiSinh_BacDaoTaos on a.MaTS equals c.MaTS
                                join d in db.TbBacDaoTaos on c.MaBacDT equals d.MaBacDT
                                join f in db.TbHuyens on a.MaHuyen equals f.MaHuyen
                                join o in db.TbTinhs on f.MaTinh equals o.MaTinh
                                join g in db.TbDoiTuongUuTiens on a.MaDoiTuong equals g.MaDoiTuong
                                join h in db.TbTruongDHs on a.MaTruongDH equals h.MaTruongDH
                                join i in db.TbChuyenNganhs on a.MaChuyenNganh equals i.MaChuyenNganh
                                join k in db.TbNganhs on i.IDNganh equals k.IDNganh
                                join l in db.TbKhoiThis on k.MaKhoiThi equals l.MaKhoiThi
                                where c.DKThem == false

                                select new ResultTK
                                {
                                    MaTS = a.MaTS,
                                    HoDem = a.HoDem,
                                    Ten = a.Ten,
                                    FullName = a.HoDem + a.Ten,
                                    SBD = a.SBD,
                                    MaDanToc = a.MaDanToc,
                                    TenDanToc = b.TenDanToc,
                                    GioiTinh = a.GioiTinh,
                                    SoDienThoai = a.SoDienThoai,
                                    Email = a.Email,
                                    NgaySinh = a.NgaySinh,
                                    //IDTruong = a.IDTruong,
                                    //MaTruong = c.MaTruong,
                                    //TenTruong = c.TenTruong,
                                    MaHuyen = a.MaHuyen,
                                    TenHuyen = f.TenHuyen,
                                    DiaChi = a.DiaChi,
                                    DiemLop10 = a.DiemLop10,
                                    DiemLop11 = a.DiemLop11,
                                    DiemLop12 = a.DiemLop12,
                                    DiemTBTHPT = a.DiemTBTHPT,
                                    DiemTBTN = a.DiemTBTN,
                                    MaDoiTuong = a.MaDoiTuong,
                                    TenDoiTuong = g.TenDoiTuong,
                                    //MaTinhTruong = c.MaTinh,
                                    //TenTinhTruong = d.TenTinh,
                                    MaTinh = f.MaTinh,
                                    TenTinh = o.TenTinh,
                                    MaChuyenNganh = a.MaChuyenNganh,
                                    //MaHeDaoTao = a.MaHeDaoTao,
                                    MaKhoiThi = l.MaKhoiThi,
                                    TenKhoiThi = l.TenKhoiThi,
                                    MaNganh = k.MaNganh,
                                    TenChuyenNganh = i.TenChuyenNganh,
                                    TenNganh = k.TenNganh,
                                    //TenHeDaoTao = m.TenHeDaoTao,
                                    //TenBacDaoTao=
                                    NgayDangKy = a.NgayDangKi,
                                    HinhThucDK = a.HinhThucDK,
                                    NgayDongTien = a.NgayDongTien,
                                    NgayHoanThanhDK = a.NgayHoanThanhDK,
                                    NamTotNghiep = a.NamTotNghiep,
                                    TenBacDaoTao = d.TenBacDT + " - " + d.TbHeDaoTao.TenHeDaoTao
                                };
            return Json(CandidateList.ToList(),JsonRequestBehavior.AllowGet);
        }
        public ActionResult EditingPopup_ReadCandidateList([DataSourceRequest] DataSourceRequest request)
        {
            var CandidateList = (from a in db.TbThiSinhs
                                join b in db.TbDanTocs on a.MaDanToc equals b.MaDanToc
                                join c in db.TbThiSinh_BacDaoTaos on a.MaTS equals c.MaTS
                                join d in db.TbBacDaoTaos on c.MaBacDT equals d.MaBacDT
                                join e in db.TbThiSinh_Truongs on a.MaTS equals e.MaTS
                                join j in db.TbTruongTHPTs on e.IDTruong equals j.IDTruong
                                join x in db.TbTinhs on j.MaTinh equals x.MaTinh
                                join f in db.TbHuyens on a.MaHuyen equals f.MaHuyen
                                join o in db.TbTinhs on f.MaTinh equals o.MaTinh
                                join g in db.TbDoiTuongUuTiens on a.MaDoiTuong equals g.MaDoiTuong
                                join h in db.TbTruongDHs on a.MaTruongDH equals h.MaTruongDH
                                join i in db.TbChuyenNganhs on a.MaChuyenNganh equals i.MaChuyenNganh
                                join k in db.TbNganhs on i.IDNganh equals k.IDNganh
                                join l in db.TbKhoiThis on k.MaKhoiThi equals l.MaKhoiThi                            
                                where c.DKThem==false 

                                select new 
                                {
                                    MaTS = a.MaTS,
                                    HoDem = a.HoDem,
                                    Ten = a.Ten,
                                    FullName = a.HoDem + a.Ten,
                                    SBD = a.SBD,
                                    MaDanToc = a.MaDanToc,
                                    TenDanToc = b.TenDanToc,
                                    GioiTinh = a.GioiTinh,
                                    SoDienThoai = a.SoDienThoai,
                                    Email = a.Email,
                                    NgaySinh = a.NgaySinh,
                                    TenTinhTruong10 = from aa in db.TbThiSinh_Truongs 
                                                      join bb in db.TbTruongTHPTs on aa.IDTruong equals bb.IDTruong
                                                      join cc in db.TbTinhs on bb.MaTinh equals cc.MaTinh
                                                      where aa.Lop == 10 && aa.MaTS == a.MaTS
                                                      select cc.TenTinh,
                                    TenTruong10 = from aa in db.TbThiSinh_Truongs 
                                                      join bb in db.TbTruongTHPTs on aa.IDTruong equals bb.IDTruong
                                                      where aa.Lop == 10 && aa.MaTS == a.MaTS
                                                      select bb.TenTruong,
                                    TenTinhTruong11 = from aa in db.TbThiSinh_Truongs
                                                      join bb in db.TbTruongTHPTs on aa.IDTruong equals bb.IDTruong
                                                      join cc in db.TbTinhs on bb.MaTinh equals cc.MaTinh
                                                      where aa.Lop == 11 && aa.MaTS == a.MaTS
                                                      select cc.TenTinh,
                                    TenTruong11 = from aa in db.TbThiSinh_Truongs
                                                  join bb in db.TbTruongTHPTs on aa.IDTruong equals bb.IDTruong
                                                  where aa.Lop == 11 && aa.MaTS == a.MaTS
                                                  select bb.TenTruong,
                                    TenTinhTruong12 = from aa in db.TbThiSinh_Truongs
                                                      join bb in db.TbTruongTHPTs on aa.IDTruong equals bb.IDTruong
                                                      join cc in db.TbTinhs on bb.MaTinh equals cc.MaTinh
                                                      where aa.Lop == 12 && aa.MaTS == a.MaTS
                                                      select cc.TenTinh,
                                    TenTruong12 = from aa in db.TbThiSinh_Truongs
                                                  join bb in db.TbTruongTHPTs on aa.IDTruong equals bb.IDTruong
                                                  where aa.Lop == 12 && aa.MaTS == a.MaTS
                                                  select bb.TenTruong,     
                                    MaHuyen = a.MaHuyen,
                                    TenHuyen = f.TenHuyen,
                                    DiaChi = a.DiaChi,
                                    MaDoiTuong = a.MaDoiTuong,
                                    TenDoiTuong = g.TenDoiTuong,
                                    MaTinh = f.MaTinh,
                                    TenTinh = o.TenTinh,
                                    MaChuyenNganh = a.MaChuyenNganh,
                                    MaKhoiThi = l.MaKhoiThi,
                                    TenKhoiThi = l.TenKhoiThi,
                                    MaNganh = k.MaNganh,
                                    TenChuyenNganh = i.TenChuyenNganh,
                                    TenNganh = k.TenNganh,                                   
                                    NgayDangKy = a.NgayDangKi,
                                    HinhThucDK = a.HinhThucDK,
                                    NgayDongTien = a.NgayDongTien,
                                    NgayHoanThanhDK = a.NgayHoanThanhDK,
                                    TenBacDaoTao= d.TenBacDT, 
                                    TenHeDaoTao = d.TbHeDaoTao.TenHeDaoTao
                                }).GroupBy(m => m.MaTS).Select(m => m.FirstOrDefault());
            return Json(CandidateList.ToDataSourceResult(request));
        }

        public ActionResult EditingPopup_ReadDiem([DataSourceRequest] DataSourceRequest request)
        {
            var CandidateList = from a in db.TbThiSinhs                              
                                                             
                                select new ResultTK
                                {
                                    MaTS = a.MaTS,
                                    HoDem = a.HoDem,
                                    Ten = a.Ten,
                                    FullName = a.HoDem + a.Ten,
                                    SBD = a.SBD,                                 
                                    GioiTinh = a.GioiTinh,
                                    SoDienThoai = a.SoDienThoai,
                                    Email = a.Email,
                                    NgaySinh = a.NgaySinh,                         
                                    DiaChi = a.DiaChi,
                                    DiemLop10 = a.DiemLop10,
                                    DiemLop11 = a.DiemLop11,
                                    DiemLop12 = a.DiemLop12,
                                    DiemTBTHPT = a.DiemTBTHPT,
                                    DiemTBTN = a.DiemTBTN,                                     
                                    HinhThucDK = a.HinhThucDK,  
                                    MaMon=0,         
                                    DiemTN=""
                                };
            List<ResultTK> data=new List<ResultTK>();
            foreach (var item in CandidateList)
            {
              data.Add( new ResultTK
                {
                    MaTS = item.MaTS,
                    HoDem = item.HoDem,
                    Ten = item.Ten,
                    FullName = item.HoDem + item.Ten,
                    SBD = item.SBD,
                    GioiTinh = item.GioiTinh,
                    SoDienThoai = item.SoDienThoai,
                    Email = item.Email,
                    NgaySinh = item.NgaySinh,
                    DiaChi = item.DiaChi,
                    DiemLop10 = item.DiemLop10,
                    DiemLop11 = item.DiemLop11,
                    DiemLop12 = item.DiemLop12,
                    DiemTBTHPT = item.DiemTBTHPT,
                    DiemTBTN = item.DiemTBTN,
                    HinhThucDK = item.HinhThucDK,
                    MaMon = 0,
                    DiemTN = DiemTN(item.MaTS)
                });             
            }
            return Json(data.ToDataSourceResult(request));
        }

        string DiemTN(string MaTS)
        {
            string str = "";
            var data = db.TbDiemTotNghieps.Include(e => e.TbMonTotNghiep).Where(e => e.MaTS == MaTS);
            foreach (var item in data)
            {
                str += item.TbMonTotNghiep.TenMon + ": " + item.Diem + " , ";
            }
            return str;
        }

        public ActionResult UpdateDiem(string MaTS, float DiemLop10,float DiemLop11,float DiemLop12)
        {
            var InfoCandidate = db.TbThiSinhs.AsNoTracking().First(n => n.MaTS == MaTS);             
            InfoCandidate.DiemLop10 = DiemLop10;
            InfoCandidate.DiemLop11 = DiemLop11;
            InfoCandidate.DiemLop12 = DiemLop12;

            //Tinh diem TBTHPT
            db.Entry(InfoCandidate).State = EntityState.Modified;

            TbDiemTotNghiep diem;
            //môn còn lại
            if (Request.Form["Subject"] != null && Request.Form["Mark"] != null)
            {
                string[] MangMaMon2 = Request.Form["Subject"].Split(',');
                string[] MangDiemMon2 = Request.Form["Mark"].Split(',');
                for (int i = 0; i < MangMaMon2.Length; i++)
                {
                    if (MangDiemMon2[i].Trim() != "")
                    {
                        diem = new TbDiemTotNghiep { MaTS = MaTS, MaMon = Int32.Parse(MangMaMon2[i]), Diem = double.Parse(MangDiemMon2[i]) };
                        db.Entry(diem).State = EntityState.Modified;
                    }
                }

                //Tinh diem TBTN
            }

            db.SaveChanges();

            return RedirectToAction("QuanLyDiem");
        }

        public ActionResult EditingPopup_DestroyCandidateList([DataSourceRequest] DataSourceRequest request, TbThiSinh data)
        {
            Session["current_url"] = Request.Url.AbsoluteUri;
            if (!CheckRole.IsRole("candidate_d", Session["Function"] as string[]))
                return this.Json(new DataSourceResult { Errors = "Bạn không có quyền thực hiện chức năng này!" });

            if (data != null)
            {
                TbNguoiDung itemuser = db.TbNguoiDungs.FirstOrDefault(item => item.TenDangNhap == data.MaTS);
                if (itemuser != null)
                {
                    db.TbNguoiDungs.Remove(itemuser);
                }
                var itemtraining = db.TbThiSinh_BacDaoTaos.Where(item => item.MaTS == data.MaTS);
                if (itemtraining != null)
                {
                    foreach (var a in itemtraining)
                    {
                        db.TbThiSinh_BacDaoTaos.Remove(a);
                    }
                }
                var itemhighschool = db.TbThiSinh_Truongs.Where(item => item.MaTS == data.MaTS);
                if (itemhighschool != null)
                {
                    foreach (var a in itemhighschool)
                    {
                        db.TbThiSinh_Truongs.Remove(a);
                    }
                }
                var itemmark = db.TbDiemTotNghieps.Where(item => item.MaTS == data.MaTS);
                if (itemmark != null)
                {
                    foreach (var a in itemmark)
                    {
                        db.TbDiemTotNghieps.Remove(a);
                    }
                }
                TbThiSinh itemdata = db.TbThiSinhs.FirstOrDefault(item => item.MaTS == data.MaTS);
                db.TbThiSinhs.Remove(itemdata);
                db.SaveChanges();
            }
            return Json(ModelState.ToDataSourceResult());
        }

        private void SaveChanges(DbContext context)
        {
            try
            {
                context.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                StringBuilder sb = new StringBuilder();

                foreach (var failure in ex.EntityValidationErrors)
                {
                    sb.AppendFormat("{0} failed validation\n", failure.Entry.Entity.GetType());
                    foreach (var error in failure.ValidationErrors)
                    {
                        sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage);
                        sb.AppendLine();
                    }
                }

                throw new DbEntityValidationException(
                    "Entity Validation Failed - errors follow:\n" +
                    sb.ToString(), ex
                ); // Add the original exception as the innerException
            }
        }
        public ActionResult Excel_Export_Save(string contentType, string base64, string fileName)
        {
            var fileContents = Convert.FromBase64String(base64);

            return File(fileContents, contentType, fileName);
        }
        public ActionResult ImportCandidate(HttpPostedFileBase FileImport)
        {

            bool state = false;
            if (FileImport != null)
            {
                // thuc hien thao tac tai day
                if (FileImport.ContentLength > 0)
                {
                    string Extension = System.IO.Path.GetExtension(FileImport.FileName);
                    if (Extension == ".xls" || Extension == ".xlsx")
                    {
                        string path = string.Concat(Server.MapPath("~/Uploads/File/" + DateTime.Now.ToString("MMddyyyyHHmmssfff") + FileImport.FileName));
                        FileImport.SaveAs(path);
                        OleDbConnection oledbcon = new OleDbConnection("provider=microsoft.ace.oledb.12.0;data source=" + path + ";extended properties=excel 12.0;");
                        oledbcon.Open();
                        DataTable ExcelSheets = oledbcon.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
                        string SpreadSheetName = ExcelSheets.Rows[0]["TABLE_NAME"].ToString();
                        OleDbCommand oledbcmd = new OleDbCommand("Select * from [" + SpreadSheetName + "]", oledbcon);
                        OleDbDataAdapter oledbda = new OleDbDataAdapter(oledbcmd);
                        DataTable dt = new DataTable();
                        TbThiSinh item;
                        TbNguoiDung nguoidung;
                        oledbda.Fill(dt);
                        var ListHighSchool = (from c in db.TbTruongTHPTs select c).ToList();
                        var ListProvince = (from c in db.TbTinhs select c).ToList();
                        var ListCandidate = (from c in db.TbThiSinhs select c).ToList();
                        var ListCommune = (from c in db.TbHuyens select c).ToList();

                        if (dt.Rows.Count > 0)
                        {
                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                if (!dt.Columns.Contains("ho"))
                                {
                                    mess.Add(new SelectListItem { Text = "Cột Họ không tồn tại!" });
                                    goto next;
                                }
                                string Truong10 = dt.Rows[i]["lop10"].ToString().Trim().Substring(2, dt.Rows[i]["lop10"].ToString().Length - 2);
                                string Tinh10 = dt.Rows[i]["lop10"].ToString().Trim().Substring(0, dt.Rows[i]["lop10"].ToString().Length - 3);
                                string Truong11 = dt.Rows[i]["lop11"].ToString().Trim().Substring(2, dt.Rows[i]["lop11"].ToString().Length - 2);
                                string Tinh11 = dt.Rows[i]["lop11"].ToString().Trim().Substring(0, dt.Rows[i]["lop11"].ToString().Length - 3);
                                string Truong12 = dt.Rows[i]["lop12"].ToString().Trim().Substring(2, dt.Rows[i]["lop12"].ToString().Length - 2);
                                string Tinh12 = dt.Rows[i]["lop12"].ToString().Trim().Substring(0, dt.Rows[i]["lop12"].ToString().Length - 3);
                                string Ngay = dt.Rows[i]["ngaysinh"].ToString().Trim().Substring(0, 2);
                                string Thang = dt.Rows[i]["ngaysinh"].ToString().Trim().Substring(2, 2);
                                string Nam = dt.Rows[i]["ngaysinh"].ToString().Trim().Substring(4, 2);
                                string NgaySinh = (Thang + "/" + Ngay + "/19" + Nam);

                                // *************doan nay la gi, 2 doan giong nhau the ************

                                foreach (var a in ListHighSchool)
                                {
                                    CheckHighSchool10 = false;

                                    if (a.MaTruong.ToLower().Trim() == Truong10.ToLower().Trim() && a.MaTinh.ToLower().Trim() == Tinh10.ToLower().Trim())
                                    {
                                        CheckHighSchool10 = true;
                                        idtruong10 = a.IDTruong;
                                        break;
                                        //goto next11;
                                    }
                                }
                                foreach (var a in ListHighSchool)
                                {
                                    CheckHighSchool11 = false;
                                    if (a.MaTruong.ToLower().Trim() == Truong11.ToLower().Trim() && a.MaTinh.ToLower().Trim() == Tinh11.ToLower().Trim())
                                    {
                                        CheckHighSchool11 = true;
                                        idtruong11 = a.IDTruong;
                                        break;
                                        //goto next12;
                                    }
                                }
                                    //next12:
                                foreach (var a in ListHighSchool)
                                {
                                    CheckHighSchool12 = false;
                                    if (a.MaTruong.ToLower().Trim() == Truong12.ToLower().Trim() && a.MaTinh.ToLower().Trim() == Tinh12.ToLower().Trim())
                                    {
                                        CheckHighSchool12 = true;
                                        idtruong12 = a.IDTruong;
                                        break;
                                    }
                                }            

                                // gop 3 vong check vao 1
                                // ban dau gan bang false, neu cai nao do thoa man yeu cau thi se co gia tri dung, neu ko van la false
                                //CheckHighSchool10 = false;
                                //CheckHighSchool11 = false;
                                //CheckHighSchool12 = false;
                                //foreach (var a in ListHighSchool)
                                //{                                    
                                //    if (a.MaTruong.ToLower().Trim() == Truong10 && a.MaTinh.ToLower().Trim() == Tinh10)
                                //    {
                                //        CheckHighSchool10 = true;
                                //        idtruong10 = a.IDTruong;        
                                //    }

                                //    if (a.MaTruong.ToLower().Trim() == Truong11 && a.MaTinh.ToLower().Trim() == Tinh11)
                                //    {
                                //        CheckHighSchool11 = true;
                                //        idtruong11 = a.IDTruong;                                        
                                //    }

                                //    if (a.MaTruong.ToLower().Trim() == Truong12 && a.MaTinh.ToLower().Trim() == Tinh12)
                                //    {
                                //        CheckHighSchool12 = true;
                                //        idtruong12 = a.IDTruong;
                                //    }                                
                                //}
                                
                                if (!CheckHighSchool10)
                                {
                                    mess.Add(new SelectListItem { Text = "Trường: " + Truong10 + " thuộc Tỉnh " + Tinh10 + " không tồn tại!" });
                                }
                                if (!CheckHighSchool11)
                                {
                                    mess.Add(new SelectListItem { Text = "Trường: " + Truong11 + " thuộc Tỉnh " + Tinh11 + " không tồn tại!" });
                                }
                                if (!CheckHighSchool12)
                                {
                                    mess.Add(new SelectListItem { Text = "Trường: " + Truong12 + " thuộc Tỉnh " + Tinh12 + " không tồn tại!" });
                                }

                                CheckProvince = false;
                                foreach (var a in ListProvince)
                                {                                  
                                    if (a.MaTinh.ToLower().Trim() == dt.Rows[i]["tinh"].ToString().ToLower().Trim())
                                    {
                                        CheckProvince = true;
                                        //Province = a.TenTinh.Trim();
                                        break;
                                    }
                                }
                                if (!CheckProvince)
                                {
                                    mess.Add(new SelectListItem { Text = "Tỉnh " + dt.Rows[i]["tinh"].ToString() + " không tồn tại!" });
                                }

                                // dua het dieu kien ban dau =false ra ngoai, ko de trog vog lap

                                CheckCommune = false;
                                foreach (var a in ListCommune)
                                {                                   
                                    if (a.MaHuyen.ToLower().Trim() == dt.Rows[i]["huyen"].ToString().ToLower().Trim() &&
                                        a.MaTinh.ToLower().Trim() == dt.Rows[i]["tinh"].ToString().ToLower().Trim())
                                    {
                                        CheckCommune = true;
                                        break;
                                    }
                                }
                                if (!CheckCommune)
                                {
                                    mess.Add(new SelectListItem { Text = "Tỉnh " + dt.Rows[i]["tinh"].ToString() + " không có Huyện " + dt.Rows[i]["huyen"].ToString() + "!" });
                                }
                                foreach (var a in ListCandidate)
                                {
                                    CheckCandidate = false;
                                    if (a.CMND.ToLower().Trim() == dt.Rows[i]["sobaodanh"].ToString().ToLower().Trim())
                                    {
                                        CheckCandidate = true;
                                        break;
                                    }
                                }
                                if (CheckCandidate)
                                {
                                    mess.Add(new SelectListItem { Text = "Thí sinh " + dt.Rows[i]["ho"].ToString().Trim() + " " + dt.Rows[i]["ten"].ToString().Trim() + " đã tồn tại!" });
                                }
                                if (CheckProvince && CheckHighSchool10 && CheckHighSchool11 && CheckHighSchool12 && CheckCommune && !CheckCandidate)
                                {
                                    item = new TbThiSinh();
                                    item.MaTS = GetID();

                                    item.HoDem = dt.Rows[i]["ho"].ToString().Trim();
                                    item.Ten = dt.Rows[i]["ten"].ToString().Trim();
                                    if (dt.Rows[i]["phai"].ToString().Trim() == "0")
                                    {
                                        item.GioiTinh = GioiTinh.Nam;
                                    }
                                    else
                                    {
                                        item.GioiTinh = GioiTinh.Nữ;
                                    }
                                    item.NgaySinh = DateTime.Parse(NgaySinh);
                                    item.MaDanToc = 1;
                                    item.DiaChi = Province;
                                    item.CMND = dt.Rows[i]["sobaodanh"].ToString().Trim();
                                    item.SBD = dt.Rows[i]["sobaodanh"].ToString().Trim();
                                    item.MaDoiTuong = Int32.Parse(dt.Rows[i]["nhomut"].ToString().Trim());
                                    //item.MaHeDaoTao = 1;
                                    item.MaChuyenNganh = "1";
                                    //item.TrangThaiDongTien = true;
                                    item.HinhThucDK = HinhThucDK.Thi;
                                    item.NgayDangKi = DateTime.Now;
                                    string huyen = dt.Rows[i]["huyen"].ToString().Trim();
                                    string tinh = dt.Rows[i]["tinh"].ToString().Trim();
                                    item.DiaChi = db.TbHuyens.Where(m => m.MaHuyen.Trim() == huyen).First().TenHuyen + " " + db.TbTinhs.Where(m => m.MaTinh.Trim() == tinh).First().TenTinh;
                                    item.MaTruongDH = "DDL";
                                    //item.TbTruongTHPT

                                    //-------------- gan mac dinh ????????----------------
                                    item.Email = "nhatduocbitien@gmail.com";
                                    item.SoDienThoai = "0978654123";
                                    item.MaHuyen = huyen;
                                    db.TbThiSinhs.Add(item);
                                    TbThiSinh_Truong Lop10 = new TbThiSinh_Truong { MaTS = item.MaTS, IDTruong = idtruong10, Lop = 10 };
                                    db.TbThiSinh_Truongs.Add(Lop10);
                                    TbThiSinh_Truong Lop11 = new TbThiSinh_Truong { MaTS = item.MaTS, IDTruong = idtruong11, Lop = 11 };
                                    db.TbThiSinh_Truongs.Add(Lop11);
                                    TbThiSinh_Truong Lop12 = new TbThiSinh_Truong { MaTS = item.MaTS, IDTruong = idtruong12, Lop = 12 };
                                    db.TbThiSinh_Truongs.Add(Lop12);
                                    db.TbThiSinh_BacDaoTaos.Add(new TbThiSinh_BacDaoTao { MaTS = item.MaTS, DKThem = false, MaBacDT = db.TbBacDaoTaos.Where(m => m.TenBacDT.Trim() == "Đại học" && m.MaHeDaoTao == 1).First().MaBacDT, TrungTuyen = null });
                                    //insert Tài khoản
                                    nguoidung = new TbNguoiDung { TenDangNhap = item.MaTS, Email = item.Email, MaQuyen = db.TbQuyens.Where(e => e.Quyen.ToLower() == "thí sinh").FirstOrDefault().MaQuyen, MatKhau = DuLieuChung.MaHoaMD5("123456"), KhoaTaiKhoan = 0 };
                                    db.TbNguoiDungs.Add(nguoidung);
                                    SaveChanges(db);
                                    No += 1;
                                }
                            }
                        next:
                            if (mess.Count() > 0)
                            {
                                state = false;
                                if (No > 0)
                                {
                                    mess.Add(new SelectListItem { Text = "Thực hiện chèn thành công " + No + " bản ghi!" });
                                }
                            }
                            else
                            {
                                state = true;
                                mess.Add(new SelectListItem { Text = "Thực hiện chèn thành công " + No + " bản ghi!" });
                            }
                        }
                        else
                        {
                            Response.Write("Không có dữ liệu!");
                        }
                        oledbcon.Close();
                    }
                    else
                    {
                        Response.Write("Bạn phải nhập file định dạng excel!");
                    }
                }
            }
            else
                mess.Add(new SelectListItem { Text = "Có lỗi!" });

            return Json(new { State = state, Message = mess.OrderBy(m=> m.Text).GroupBy(m => m.Text).Select(m => m.First()) });
        }
        public string GetID()
        {
            string ID = "";
            var MaTS = (from p in db.TbThiSinhs orderby (p.MaTS) descending select p).Take(1).FirstOrDefault();
            int Cuoi;
            string LastID;
            int NextID;

            if (MaTS == null)
            {
                NextID = 1;
            }
            else
            {
                Cuoi = Convert.ToInt32(MaTS.MaTS.ToString().Substring(4)) + 1;
                LastID = Cuoi.ToString();
                if (LastID == null)
                {
                    LastID = DateTime.Now.ToString("yyyy") + "00001";
                }
                NextID = Cuoi;
            }
            ID = DateTime.Now.ToString("yyyy") + NextID.ToString("00000");
            return ID;
        }

        #region Registration

        #region Select Training System
        [HttpGet]
        public ActionResult SelectTrainingSystem()
        {
            Session["current_url"] = Request.Url.AbsoluteUri;
            if (!CheckRole.IsRole("candidate_c", Session["Function"] as string[]) || !CheckRole.IsRole("registration", Session["Function"] as string[]))
                return Content("Bạn chưa <a href='/Admin/Home/Login'>đăng nhập hệ thống</a> hoặc không có quyền sử dụng chức năng này.");

            //ViewBag.BacDaoTao = new SelectList(db.TbBacDaoTaos.ToList(), "MaBacDT", "TenBacDT");
            ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.ToList(), "MaHeDaoTao", "TenHeDaoTao");

            if (!Request.IsAjaxRequest())
                return View();

            return PartialView();
        }
        #region Load Training System
        public JsonResult GetTLByTS(string TSID)
        {
            return Json(new SelectList(db.TbBacDaoTaos.Where(m => m.MaHeDaoTao.ToString().Trim() == TSID.Trim()).ToList(), "MaBacDT", "TenBacDT"), JsonRequestBehavior.AllowGet);
        }
        #endregion
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult SelectTrainingSystem(string id)
        {
            ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.ToList(), "MaHeDaoTao", "TenHeDaoTao");
            if (ModelState.IsValid)
            {
                int TLID = Int32.Parse(Request.Form["MaBacDT"]);
                var ListTL = db.TbBacDaoTaos.Where(m => m.MaBacDT == TLID).FirstOrDefault().TenBacDT;
                if (ListTL.ToLower().Trim() == "đại học".ToLower() || ListTL.ToLower().Trim() == "cao đẳng".ToLower())
                {
                    return RedirectToAction("RegistrationForm", "CandidateManagement", new { TrainingLevel = TLID });
                }
                return RedirectToAction("RegistrationFormVocation", "CandidateManagement", new { TrainingLevel = TLID });
            }

            return PartialView();
        }
        #endregion
        #region Get Data
        public JsonResult GetPhylumByGroup(int TLID, string makhoithi)
        {

            //int Te = Int32.Parse(Request.Form["lbTrainingSystem"]);
            var LoadTrainingLevel = db.TbBacDaoTaos.Where(m => m.MaBacDT == TLID).FirstOrDefault().TenBacDT;
            var phylumD = db.TbNganhs.Where(m => m.MaNganh.ToString().Contains("D") && m.MaKhoiThi == makhoithi);
            var phylumC = db.TbNganhs.Where(m => m.MaNganh.ToString().Contains("C") && m.MaKhoiThi == makhoithi);
            if (LoadTrainingLevel.ToLower().Trim() == "đại học")
            {
                return Json(new SelectList(phylumD.ToList(), "IDNganh", "TenNganh"), JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(new SelectList(phylumC.ToList(), "IDNganh", "TenNganh"), JsonRequestBehavior.AllowGet);
            }
        }
        public JsonResult GetProvinceByCommune(string matinh)
        {
            var commune = from c in db.TbHuyens
                          where c.MaTinh == matinh
                          select c;
            return Json(new SelectList(commune.ToList(), "MaHuyen", "TenHuyen"), JsonRequestBehavior.AllowGet);
        }
        public JsonResult GetHighSchoolByProvince(string matinh)
        {
            var highschool = from c in db.TbTruongTHPTs
                             where c.MaTinh == matinh
                             select c;
            return Json(new SelectList(highschool.ToList(), "IDTruong", "TenTruong"), JsonRequestBehavior.AllowGet);
        }
        public JsonResult GetGraduateSubjectBySubjectCustom(int mamon)
        {
            var monthi = from c in db.TbMonTotNghieps
                         where c.MaMon != mamon && c.TenMon != "Toán" && c.TenMon != "Tiếng anh" && c.TenMon != "Ngữ Văn"
                         select c;
            return Json(new SelectList(monthi.ToList(), "MaMon", "TenMon"), JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetGraduateSubjectByGroup(int mamontuychon, string makhoithi)
        {
            var monthi = from c in db.TbKhoiThi_MonTotNghieps
                         where c.TbMonTotNghiep.TenMon != "Toán" && c.TbMonTotNghiep.TenMon != "Tiếng anh" && c.TbMonTotNghiep.TenMon != "Ngữ Văn"
                               && c.TbMonTotNghiep.MaMon != mamontuychon && c.MaKhoiThi == makhoithi
                         select new
                         {
                             MaMon = c.MaMon,
                             TenMon = c.TbMonTotNghiep.TenMon
                         };

            return Json(monthi, JsonRequestBehavior.AllowGet);
        }
        public JsonResult GetGraduateSubjectByGroup2(string MaTS, string makhoithi)
        {
            var monthi = from c in db.TbKhoiThi_MonTotNghieps
                         where c.TbMonTotNghiep.TenMon != "Toán" && c.TbMonTotNghiep.TenMon != "Tiếng anh" && c.TbMonTotNghiep.TenMon != "Ngữ Văn"
                               && c.MaKhoiThi == makhoithi
                         select new
                         {
                             MaMon = c.MaMon,
                             TenMon = c.TbMonTotNghiep.TenMon
                         };
            var ListSubject = from a in db.TbThiSinhs
                              join b in db.TbDiemTotNghieps on a.MaTS equals b.MaTS
                              join c in db.TbMonTotNghieps on b.MaMon equals c.MaMon
                              where a.MaTS == MaTS
                              select b;


            return Json(monthi, JsonRequestBehavior.AllowGet);
        }
        #endregion
        #region Registration Form
        public ActionResult RegistrationForm(string MaTS, string TrainingLevel)
        {
            Session["current_url"] = Request.Url.AbsoluteUri;
            if (!CheckRole.IsRole("candidate_c", Session["Function"] as string[]) || !CheckRole.IsRole("registration", Session["Function"] as string[]))
                return Content("Bạn chưa <a href='/Admin/Home/Login'>đăng nhập hệ thống</a> hoặc không có quyền sử dụng chức năng này.");
            //ViewBag.HeDaoTaoKhac = Enum.GetValues(typeof(HeDaoTaoKhac));
            ViewBag.LienKet = false;
            ViewBag.HeTrungCap = false;
            ViewBag.HeCaoDang = false;
            ViewBag.DaDongTien = false;
            List<SelectListItem> list = new List<SelectListItem>();
            list.Add(new SelectListItem { Text = "Hà Nội", Value = "0" });
            list.Add(new SelectListItem { Text = "Trung cấp Kinh tế Kỹ thuật Hồng Lam", Value = "1" });
            ViewBag.NoiDaoTao = list.ToList();
            ViewBag.TL = TrainingLevel;
            TbThiSinh ThiSinh = new TbThiSinh();
            if (ModelState.IsValid)
            {
                if (Session["TenDangNhap"] != null)
                    MaTS = MaTS ?? Session["TenDangNhap"].ToString();

                if (ThiSinh.MaTS == null)
                {
                    ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.OrderBy(m =>m.TenHeDaoTao).ToList(), "MaHeDaoTao", "TenHeDaoTao");
                    ViewBag.Tinh = new SelectList(db.TbTinhs.OrderBy(m => m.TenTinh).ToList(), "MaTinh", "TenTinh");
                    ViewBag.MonTotNghiep = new SelectList(db.TbMonTotNghieps.Where(m => m.TenMon.ToLower() != "Toán".ToLower() && m.TenMon.ToLower() != "Ngữ văn".ToLower() && m.TenMon.ToLower() != "Tiếng Anh".ToLower()).ToList(), "MaMon", "TenMon");
                    ViewBag.TinhTruong = new SelectList(db.TbTinhs.OrderBy(m => m.TenTinh).ToList(), "MaTinh", "TenTinh");
                    //ViewBag.Huyen = new SelectList(db.TbHuyens.ToList(), "MaHuyen", "TenHuyen");
                    //ViewBag.Nganh = new SelectList(db.TbNganhs.ToList(), "IDNganh", "TenNganh");
                    //ViewBag.ChuyenNganh = new SelectList(db.TbChuyenNganhs.ToList(), "MaChuyenNganh", "TenChuyenNganh");
                    //ViewBag.TruongTHPT = new SelectList(db.TbTruongTHPTs.ToList(), "IDTruong", "TenTruong");
                    ViewBag.TruongDH = new SelectList(db.TbTruongDHs.OrderBy(m => m.TenTruongDH).ToList(), "MaTruongDH", "TenTruongDH");
                    //ViewBag.KhuVuc = new SelectList(db.TbKhuVucs.ToList(), "MaKhuVuc", "TenKhuVuc");
                    //ViewBag.XepLoaiHS = new SelectList(db.TbXepLoaiHS.ToList(), "MaXepLoaiHS", "TenXepLoaiHS");
                    ViewBag.DanToc = new SelectList(db.TbDanTocs.OrderBy(m => m.TenDanToc).ToList(), "MaDanToc", "TenDanToc");
                    ViewBag.DoiTuongUuTien = new SelectList(db.TbDoiTuongUuTiens.OrderBy(m => m.TenDoiTuong).ToList(), "MaDoiTuong", "TenDoiTuong");
                    ViewBag.KhoiThi = new SelectList(db.TbKhoiThis.OrderBy(m => m.TenKhoiThi).ToList(), "MaKhoiThi", "TenKhoiThi");
                    //ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.ToList(), "MaHeDaoTao", "TenHeDaoTao");
                }
            }


            if (Request.IsAjaxRequest() || MaTS != null)
                return PartialView(ThiSinh);

            return View(ThiSinh);
        }

        [HttpPost]
        public ActionResult RegistrationForm(TbThiSinh item, bool LienKet = false, bool HeTrungCap = false, bool HeCaoDang = false, bool DaDongTien = false)
        {
            if (item != null)
            {
                TbNguoiDung nguoidung;
                TbDiemTotNghiep diem;
                TbThiSinh_BacDaoTao CD_TL;
                item.NgayDangKi = DateTime.Now;
                
                    //if (ModelState.IsValid)
                    //{
                item.MaTS = GetID();
                if (DaDongTien)
                {
                    item.TrangThaiDongTien = true;
                    item.NgayDongTien = DateTime.Now;
                    item.TrangThaiHoanThanh = true;
                    item.NgayHoanThanhDK = DateTime.Now;
                }
                db.TbThiSinhs.Add(item);
                TbThiSinh_Truong Lop10 = new TbThiSinh_Truong { MaTS = item.MaTS, IDTruong = int.Parse(Request.Form["IDTruong10"].Trim()), Lop = 10 };
                db.TbThiSinh_Truongs.Add(Lop10);
                TbThiSinh_Truong Lop11 = new TbThiSinh_Truong { MaTS = item.MaTS, IDTruong = int.Parse(Request.Form["IDTruong11"].Trim()), Lop = 11 };
                db.TbThiSinh_Truongs.Add(Lop11);
                TbThiSinh_Truong Lop12 = new TbThiSinh_Truong { MaTS = item.MaTS, IDTruong = int.Parse(Request.Form["IDTruong12"].Trim()), Lop = 12 };
                db.TbThiSinh_Truongs.Add(Lop12);
                if (Request.Form["HinhThucDK"] == "0")
                {
                    item.MaTruongDH = "DDL";
                    TbDiemTotNghiep MonTuyChon;
                    CD_TL = new TbThiSinh_BacDaoTao { MaTS = item.MaTS, DKThem = false, MaBacDT = int.Parse(Request.Form["SendID"].Trim()), TrungTuyen = null };
                    db.TbThiSinh_BacDaoTaos.Add(CD_TL);
                    MonTuyChon = new TbDiemTotNghiep { MaMon = int.Parse(Request.Form["MaMon"].Trim()), MaTS = item.MaTS };
                    db.TbDiemTotNghieps.Add(MonTuyChon);
                    string[] thiThem = Request.Form["checkbox"].Split(',');
                    for (int i = 0; i < thiThem.Length; i++)
                    {
                        diem = new TbDiemTotNghiep { MaTS = item.MaTS, MaMon = int.Parse(thiThem[i].Trim()) };
                        db.TbDiemTotNghieps.Add(diem);
                    }
                    if (Request.Form["ChatLuongCao"] != "")
                    {
                        item.ChatLuongCao = bool.Parse(Request.Form["ChatLuongCao"].Trim());
                    }   
                }
                else if (Request.Form["HinhThucDK"] == "1")
                {
                    item.MaTruongDH = "DDL";
                    // Điểm 3 môn Toán, Văn, Anh
                    string[] MangMaMon1 = Request.Form["SubjectRecruitmentBasic"].Split(',');
                    string[] MangDiemMon1 = Request.Form["MarkRecruitmentBasic"].Split(',');
                    string ten = "";
                    for (int i = 0; i < MangMaMon1.Length; i++)
                    {
                        if (MangDiemMon1[i].Trim() != "")
                        {
                            ten = MangMaMon1[i];
                            var mamon = db.TbMonTotNghieps.Where(m => m.TenMon == ten).FirstOrDefault().MaMon;
                            diem = new TbDiemTotNghiep { MaTS = item.MaTS, MaMon = mamon, Diem = double.Parse(MangDiemMon1[i].Trim()) };
                            db.TbDiemTotNghieps.Add(diem);
                        }
                        else
                        {
                            ten = MangMaMon1[i];
                            var mamon = db.TbMonTotNghieps.Where(m => m.TenMon == ten).FirstOrDefault().MaMon;
                            diem = new TbDiemTotNghiep { MaTS = item.MaTS, MaMon = mamon };
                            db.TbDiemTotNghieps.Add(diem);
                        }

                    }
                    //Điểm môn tùy chọn
                    if (Request.Form["ddlMarkRecruitmentBasic"].Trim() != "")
                    {
                        diem = new TbDiemTotNghiep { MaTS = item.MaTS, MaMon = Int32.Parse(Request.Form["ddlSubjectRecruitmentBasic"].Trim()), Diem = double.Parse(Request.Form["ddlMarkRecruitmentBasic"].Trim()) };
                        db.TbDiemTotNghieps.Add(diem);
                    }
                    CD_TL = new TbThiSinh_BacDaoTao { MaTS = item.MaTS, DKThem = false, MaBacDT = int.Parse(Request.Form["SendID"].Trim()), TrungTuyen = null };
                    db.TbThiSinh_BacDaoTaos.Add(CD_TL);
                    //item.MaHeDaoTao = Int32.Parse(Request.Form["HDT"]);
                }
                else
                {
                    // Điểm 3 môn Toán, Văn, Anh
                    string[] MangMaMon1 = Request.Form["SubjectRecruitment"].Split(',');
                    string[] MangDiemMon1 = Request.Form["MarkRecruitment"].Split(',');
                    string ten = "";
                    for (int i = 0; i < MangMaMon1.Length; i++)
                    {
                        if (MangDiemMon1[i].Trim() != "")
                        {
                            ten = MangMaMon1[i];
                            var mamon = db.TbMonTotNghieps.Where(m => m.TenMon == ten).FirstOrDefault().MaMon;
                            diem = new TbDiemTotNghiep { MaTS = item.MaTS, MaMon = mamon, Diem = double.Parse(MangDiemMon1[i].Trim()) };
                            db.TbDiemTotNghieps.Add(diem);
                        }
                        else
                        {
                            ten = MangMaMon1[i];
                            var mamon = db.TbMonTotNghieps.Where(m => m.TenMon == ten).FirstOrDefault().MaMon;
                            diem = new TbDiemTotNghiep { MaTS = item.MaTS, MaMon = mamon };
                            db.TbDiemTotNghieps.Add(diem);
                        }

                    }
                    //Điểm môn tùy chọn
                    if (Request.Form["ddlMarkRecruitment"].Trim() != "")
                    {
                        diem = new TbDiemTotNghiep { MaTS = item.MaTS, MaMon = Int32.Parse(Request.Form["ddlSubjectRecruitment"].Trim()), Diem = double.Parse(Request.Form["ddlMarkRecruitment"].Trim()) };
                        db.TbDiemTotNghieps.Add(diem);
                    }
                    // Điểm môn thi thêm
                    if (Request.Form["IDInput"] != null && Request.Form["MarkSubject"] != null)
                    {
                        string[] MangMaMon3 = Request.Form["IDInput"].Split(',');
                        string[] MangDiemMon3 = Request.Form["MarkSubject"].Split(',');
                        for (int i = 0; i < MangMaMon3.Length; i++)
                        {
                            if (MangDiemMon3[i].Trim() != "")
                            {
                                diem = new TbDiemTotNghiep { MaTS = item.MaTS, MaMon = Int32.Parse(MangMaMon3[i]), Diem = double.Parse(MangDiemMon3[i]) };
                                db.TbDiemTotNghieps.Add(diem);
                            }
                            else
                            {
                                diem = new TbDiemTotNghiep { MaTS = item.MaTS, MaMon = Int32.Parse(MangMaMon3[i]) };
                                db.TbDiemTotNghieps.Add(diem);
                            }
                        }
                    }
                    CD_TL = new TbThiSinh_BacDaoTao { MaTS = item.MaTS, DKThem = false, MaBacDT = int.Parse(Request.Form["SendID"].Trim()), TrungTuyen = null };
                    db.TbThiSinh_BacDaoTaos.Add(CD_TL);
                }
                if (LienKet)
                {
                    item.LienKetQT = true;
                }
                if (HeCaoDang)
                {
                    var Ma1 = (from a in db.TbBacDaoTaos
                               join b in db.TbHeDaoTaos on a.MaHeDaoTao equals b.MaHeDaoTao
                               where b.TenHeDaoTao.ToLower().Trim() == "nghề" && a.TenBacDT.ToLower().Trim() == "cao đẳng"
                               select a.MaBacDT).First();
                    db.TbThiSinh_BacDaoTaos.Add(new TbThiSinh_BacDaoTao { MaBacDT = Ma1, MaTS = item.MaTS, DKThem = true, NoiDaoTao = int.Parse(Request.Form["NoiDaoTao"].Trim()), TrungTuyen = null });
                }
                if (HeTrungCap)
                {
                    var Ma2 = (from a in db.TbBacDaoTaos
                               join b in db.TbHeDaoTaos on a.MaHeDaoTao equals b.MaHeDaoTao
                               where b.TenHeDaoTao.ToLower().Trim() == "chính quy" && a.TenBacDT.ToLower().Trim() == "trung cấp"
                               select a.MaBacDT).First();
                    db.TbThiSinh_BacDaoTaos.Add(new TbThiSinh_BacDaoTao { MaBacDT = Ma2, MaTS = item.MaTS, DKThem = true, NoiDaoTao = int.Parse(Request.Form["NoiDaoTao"].Trim()), TrungTuyen = null });
                }
                db.TbThiSinhs.Add(item);

                nguoidung = new TbNguoiDung { TenDangNhap = item.MaTS,Email=item.Email, MaQuyen = db.TbQuyens.Where(e => e.Quyen.ToLower() == "thí sinh").FirstOrDefault().MaQuyen, MatKhau = DuLieuChung.MaHoaMD5("123456"), KhoaTaiKhoan = 0 };
                db.TbNguoiDungs.Add(nguoidung);
                SaveChanges(db);
                    //}                    
            }

            if (DaDongTien)
                return RedirectToAction("PhieuHoanThanh", new { MaTS = item.MaTS });

            return RedirectToAction("PhieuXacNhan", new { MaTS = item.MaTS });
        }

        public ActionResult PhieuHoanThanh(string MaTS)
        {
            return View(db.TbThiSinhs.First(e => e.MaTS == MaTS));
        }

        public ActionResult PhieuXacNhan(string MaTS)
        {
            return View(db.TbThiSinhs.First(e => e.MaTS == MaTS));
        }

        public ActionResult Step2_Examination()
        {
            //TbThiSinh ThiSinh = new TbThiSinh();
            //if (ModelState.IsValid)
            //{
            //    if (Session["TenDangNhap"] != null)
            //        MaTS = MaTS ?? Session["TenDangNhap"].ToString();

            //    if (MaTS == null)
            //    {
            List<SelectListItem> list = new List<SelectListItem>();
            list.Add(new SelectListItem { Text = "Có", Value = "True" });
            list.Add(new SelectListItem { Text = "Không", Value = "False" });
            ViewBag.ChatLuongCao = list.ToList();
            ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.Where(m => m.TenHeDaoTao.Trim() == "chính quy" || m.TenHeDaoTao.Trim() == "liên thông").ToList(), "MaHeDaoTao", "TenHeDaoTao");
            //ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.ToList(), "MaHeDaoTao", "TenHeDaoTao");
            //ViewBag.Tinh = new SelectList(db.TbTinhs.ToLisrt(), "MaTinh", "TenTinh");
            ViewBag.MonTotNghiep = new SelectList(db.TbMonTotNghieps.Where(m => m.TenMon.ToLower() != "Toán".ToLower() && m.TenMon.ToLower() != "Ngữ văn".ToLower() && m.TenMon.ToLower() != "Tiếng Anh".ToLower()).ToList(), "MaMon", "TenMon");
            //ViewBag.TinhTruong = new SelectList(db.TbTinhs.ToList(), "MaTinh", "TenTinh");
            //ViewBag.Huyen = new SelectList(db.TbHuyens.ToList(), "MaHuyen", "TenHuyen");
            //ViewBag.Nganh = new SelectList(db.TbNganhs.ToList(), "IDNganh", "TenNganh");
            //ViewBag.ChuyenNganh = new SelectList(db.TbChuyenNganhs.ToList(), "MaChuyenNganh", "TenChuyenNganh");
            //ViewBag.TruongTHPT = new SelectList(db.TbTruongTHPTs.ToList(), "IDTruong", "TenTruong");
            //ViewBag.TruongDH = new SelectList(db.TbTruongDHs.ToList(), "MaTruongDH", "TenTruongDH");
            //ViewBag.KhuVuc = new SelectList(db.TbKhuVucs.ToList(), "MaKhuVuc", "TenKhuVuc");
            //ViewBag.XepLoaiHS = new SelectList(db.TbXepLoaiHS.ToList(), "MaXepLoaiHS", "TenXepLoaiHS");
            //ViewBag.DanToc = new SelectList(db.TbDanTocs.ToList(), "MaDanToc", "TenDanToc");
            //ViewBag.DoiTuongUuTien = new SelectList(db.TbDoiTuongUuTiens.ToList(), "MaDoiTuong", "TenDoiTuong");
            ViewBag.KhoiThi = new SelectList(db.TbKhoiThis.ToList(), "MaKhoiThi", "TenKhoiThi");
            //ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.ToList(), "MaHeDaoTao", "TenHeDaoTao");

            if (Request.IsAjaxRequest())
                return PartialView();

            return View();
        }
        public ActionResult Step2_Recruiting()
        {
            //TbThiSinh ThiSinh = new TbThiSinh();
            //if (ModelState.IsValid)
            //{
            //    if (Session["TenDangNhap"] != null)
            //        MaTS = MaTS ?? Session["TenDangNhap"].ToString();

            //    if (MaTS == null)
            //    {
            List<SelectListItem> list = new List<SelectListItem>();
            list.Add(new SelectListItem { Text = "Có", Value = "True" });
            list.Add(new SelectListItem { Text = "Không", Value = "False" });
            ViewBag.ChatLuongCao = list.ToList();
            ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.Where(m => m.TenHeDaoTao.Trim() == "chính quy" || m.TenHeDaoTao.Trim() == "liên thông").ToList(), "MaHeDaoTao", "TenHeDaoTao");
            //ViewBag.Tinh = new SelectList(db.TbTinhs.ToList(), "MaTinh", "TenTinh");
            ViewBag.MonTotNghiep = new SelectList(db.TbMonTotNghieps.Where(m => m.TenMon.ToLower() != "Toán".ToLower() && m.TenMon.ToLower() != "Ngữ văn".ToLower() && m.TenMon.ToLower() != "Tiếng Anh".ToLower()).ToList(), "MaMon", "TenMon");
            //ViewBag.TinhTruong = new SelectList(db.TbTinhs.ToList(), "MaTinh", "TenTinh");
            //ViewBag.Huyen = new SelectList(db.TbHuyens.ToList(), "MaHuyen", "TenHuyen");
            ViewBag.Nganh = new SelectList(db.TbNganhs.ToList(), "IDNganh", "TenNganh");
            ViewBag.ChuyenNganh = new SelectList(db.TbChuyenNganhs.ToList(), "MaChuyenNganh", "TenChuyenNganh");
            //ViewBag.TruongTHPT = new SelectList(db.TbTruongTHPTs.ToList(), "IDTruong", "TenTruong");
            ViewBag.TruongDH = new SelectList(db.TbTruongDHs.ToList(), "MaTruongDH", "TenTruongDH");
            //ViewBag.KhuVuc = new SelectList(db.TbKhuVucs.ToList(), "MaKhuVuc", "TenKhuVuc");
            //ViewBag.XepLoaiHS = new SelectList(db.TbXepLoaiHS.ToList(), "MaXepLoaiHS", "TenXepLoaiHS");
            //ViewBag.DanToc = new SelectList(db.TbDanTocs.ToList(), "MaDanToc", "TenDanToc");
            //ViewBag.DoiTuongUuTien = new SelectList(db.TbDoiTuongUuTiens.ToList(), "MaDoiTuong", "TenDoiTuong");
            ViewBag.KhoiThi = new SelectList(db.TbKhoiThis.ToList(), "MaKhoiThi", "TenKhoiThi");
            //ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.ToList(), "MaHeDaoTao", "TenHeDaoTao");



            if (Request.IsAjaxRequest())
                return PartialView();

            return View();
        }
        public ActionResult Step2_RecruitingBasic()
        {
            //TbThiSinh ThiSinh = new TbThiSinh();
            //if (ModelState.IsValid)
            //{
            //    if (Session["TenDangNhap"] != null)
            //        MaTS = MaTS ?? Session["TenDangNhap"].ToString();

            //    if (MaTS == null)
            //    {
            List<SelectListItem> list = new List<SelectListItem>();
            list.Add(new SelectListItem { Text = "Có", Value = "True" });
            list.Add(new SelectListItem { Text = "Không", Value = "False" });
            ViewBag.ChatLuongCao = list.ToList();
            ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.Where(m => m.TenHeDaoTao.Trim() == "chính quy" || m.TenHeDaoTao.Trim() == "liên thông").ToList(), "MaHeDaoTao", "TenHeDaoTao");
            //ViewBag.Tinh = new SelectList(db.TbTinhs.ToList(), "MaTinh", "TenTinh");
            ViewBag.MonTotNghiep = new SelectList(db.TbMonTotNghieps.Where(m => m.TenMon.ToLower() != "Toán".ToLower() && m.TenMon.ToLower() != "Ngữ văn".ToLower() && m.TenMon.ToLower() != "Tiếng Anh".ToLower()).ToList(), "MaMon", "TenMon");
            //ViewBag.TinhTruong = new SelectList(db.TbTinhs.ToList(), "MaTinh", "TenTinh");
            //ViewBag.Huyen = new SelectList(db.TbHuyens.ToList(), "MaHuyen", "TenHuyen");
            ViewBag.Nganh = new SelectList(db.TbNganhs.ToList(), "IDNganh", "TenNganh");
            ViewBag.ChuyenNganh = new SelectList(db.TbChuyenNganhs.ToList(), "MaChuyenNganh", "TenChuyenNganh");
            //ViewBag.TruongTHPT = new SelectList(db.TbTruongTHPTs.ToList(), "IDTruong", "TenTruong");
            ViewBag.TruongDH = new SelectList(db.TbTruongDHs.ToList(), "MaTruongDH", "TenTruongDH");
            //ViewBag.KhuVuc = new SelectList(db.TbKhuVucs.ToList(), "MaKhuVuc", "TenKhuVuc");
            //ViewBag.XepLoaiHS = new SelectList(db.TbXepLoaiHS.ToList(), "MaXepLoaiHS", "TenXepLoaiHS");
            //ViewBag.DanToc = new SelectList(db.TbDanTocs.ToList(), "MaDanToc", "TenDanToc");
            //ViewBag.DoiTuongUuTien = new SelectList(db.TbDoiTuongUuTiens.ToList(), "MaDoiTuong", "TenDoiTuong");
            ViewBag.KhoiThi = new SelectList(db.TbKhoiThis.ToList(), "MaKhoiThi", "TenKhoiThi");
            //ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.ToList(), "MaHeDaoTao", "TenHeDaoTao");

            if (Request.IsAjaxRequest())
                return PartialView();

            return View();
        }
        #endregion

        #region Registration Form Vocation
        public ActionResult RegistrationFormVocation(string TrainingLevel)
        {
            Session["current_url"] = Request.Url.AbsoluteUri;
            if (!CheckRole.IsRole("candidate_c", Session["Function"] as string[]) || !CheckRole.IsRole("registration", Session["Function"] as string[]))
                return Content("Bạn chưa <a href='/Admin/Home/Login'>đăng nhập hệ thống</a> hoặc không có quyền sử dụng chức năng này.");

            TbThiSinh ThiSinh = new TbThiSinh();
            ViewBag.TL = TrainingLevel;
            ViewBag.DaDongTien = false;
            if (ModelState.IsValid)
            {
                //if (Session["TenDangNhap"] != null)
                //    MaTS = MaTS ?? Session["TenDangNhap"].ToString();

                if (ThiSinh.MaTS == null)
                {
                    ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.ToList(), "MaHeDaoTao", "TenHeDaoTao");
                    ViewBag.Tinh = new SelectList(db.TbTinhs.ToList(), "MaTinh", "TenTinh");
                    ViewBag.MonTotNghiep = new SelectList(db.TbMonTotNghieps.Where(m => m.TenMon.ToLower() != "Toán".ToLower() && m.TenMon.ToLower() != "Ngữ văn".ToLower() && m.TenMon.ToLower() != "Tiếng Anh".ToLower()).ToList(), "MaMon", "TenMon");
                    ViewBag.TinhTruong = new SelectList(db.TbTinhs.ToList(), "MaTinh", "TenTinh");
                    ViewBag.Huyen = new SelectList(db.TbHuyens.ToList(), "MaHuyen", "TenHuyen");
                    ViewBag.Nganh = new SelectList(db.TbNganhs.ToList(), "IDNganh", "TenNganh");
                    ViewBag.ChuyenNganh = new SelectList(db.TbChuyenNganhs.ToList(), "MaChuyenNganh", "TenChuyenNganh");
                    //ViewBag.TruongTHPT = new SelectList(db.TbTruongTHPTs.ToList(), "IDTruong", "TenTruong");
                    //ViewBag.TruongDH = new SelectList(db.TbTruongDHs.ToList(), "MaTruongDH", "TenTruongDH");
                    ViewBag.KhuVuc = new SelectList(db.TbKhuVucs.ToList(), "MaKhuVuc", "TenKhuVuc");
                    ViewBag.XepLoaiHS = new SelectList(db.TbXepLoaiHS.ToList(), "MaXepLoaiHS", "TenXepLoaiHS");
                    ViewBag.DanToc = new SelectList(db.TbDanTocs.ToList(), "MaDanToc", "TenDanToc");
                    ViewBag.DoiTuongUuTien = new SelectList(db.TbDoiTuongUuTiens.ToList(), "MaDoiTuong", "TenDoiTuong");
                    ViewBag.KhoiThi = new SelectList(db.TbKhoiThis.ToList(), "MaKhoiThi", "TenKhoiThi");
                    ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.ToList(), "MaHeDaoTao", "TenHeDaoTao");
                }
            }


            if (Request.IsAjaxRequest())
                return PartialView(ThiSinh);

            return View(ThiSinh);
        }

        [HttpPost]
        public ActionResult RegistrationFormVocation(TbThiSinh item, bool DaDongTien = false)
        {
            if (item != null)
            {
                TbNguoiDung nguoidung;
                item.NgayDangKi = DateTime.Now;
                
                item.MaTS = GetID();
                item.NgayDongTien = DateTime.Now;
                item.NgayHoanThanhDK = DateTime.Now;
                item.TrangThaiDongTien = DaDongTien;
                if (DaDongTien)
                {
                    item.TrangThaiHoanThanh = true;
                }
                item.MaTruongDH = "DDL";
                // Save High School
                
                db.TbThiSinhs.Add(item);
                TbThiSinh_Truong Lop10 = new TbThiSinh_Truong { MaTS = item.MaTS, IDTruong = int.Parse(Request.Form["IDTruong10"].Trim()), Lop = 10 };
                db.TbThiSinh_Truongs.Add(Lop10);
                TbThiSinh_Truong Lop11 = new TbThiSinh_Truong { MaTS = item.MaTS, IDTruong = int.Parse(Request.Form["IDTruong11"].Trim()), Lop = 11 };
                db.TbThiSinh_Truongs.Add(Lop11);
                TbThiSinh_Truong Lop12 = new TbThiSinh_Truong { MaTS = item.MaTS, IDTruong = int.Parse(Request.Form["IDTruong12"].Trim()), Lop = 12 };
                db.TbThiSinh_Truongs.Add(Lop12);
                nguoidung = new TbNguoiDung { TenDangNhap = item.MaTS, MaQuyen = db.TbQuyens.Where(e => e.Quyen.ToLower() == "thí sinh").FirstOrDefault().MaQuyen, Email = item.Email, MatKhau = DuLieuChung.MaHoaMD5("123456"), KhoaTaiKhoan = 0 };
                db.TbNguoiDungs.Add(nguoidung);
                SaveChanges(db);
            }


            return RedirectToAction("CandidateList", "CandidateManagement");

        }
        #endregion

        #region Edit Registration
        public ActionResult EditRegistration(string id)
        {
            Session["current_url"] = Request.Url.AbsoluteUri;
            if (!CheckRole.IsRole("candidate_u", Session["Function"] as string[]))
                return Content("Bạn chưa <a href='/Admin/Home/Login'>đăng nhập hệ thống</a> hoặc không có quyền sử dụng chức năng này.");

            ViewBag.LienKet = false;
            ViewBag.HeTrungCap = false;
            ViewBag.HeCaoDang = false;
            List<SelectListItem> list = new List<SelectListItem>();
            list.Add(new SelectListItem { Text = "Hà Nội", Value = "0" });
            list.Add(new SelectListItem { Text = "Trung cấp Kinh tế Kỹ thuật Hồng Lam", Value = "1" });
            ViewBag.NoiDaoTao = list.ToList();
            List<SelectListItem> CLC = new List<SelectListItem>();
            CLC.Add(new SelectListItem { Text = "Có", Value = "True" });
            CLC.Add(new SelectListItem { Text = "Không", Value = "False" });
            ViewBag.ChatLuongCao = CLC.ToList();
            TbThiSinh InfoCandidate = new TbThiSinh();
            InfoCandidate = db.TbThiSinhs.FirstOrDefault(m => m.MaTS == id);
            ViewBag.DanToc = new SelectList(db.TbDanTocs.ToList(), "MaDanToc", "TenDanToc", InfoCandidate.MaDanToc);
            ViewBag.DoiTuongUuTien = new SelectList(db.TbDoiTuongUuTiens.ToList(), "MaDoiTuong", "TenDoiTuong", InfoCandidate.MaDoiTuong);
            var matinh = (from c in db.TbThiSinhs
                          join d in db.TbHuyens on c.MaHuyen equals d.MaHuyen
                          //join e in db.TbTinhs on d.MaTinh equals e.MaTinh
                          where c.MaTS == id
                          select d).FirstOrDefault();
            ViewBag.Tinh = new SelectList(db.TbTinhs.ToList(), "MaTinh", "TenTinh", matinh.MaTinh);
            ViewBag.Huyen = new SelectList(db.TbHuyens.Where(m => m.MaTinh == matinh.MaTinh).ToList(), "MaHuyen", "TenHuyen", InfoCandidate.MaHuyen);
            var IDNganh = (from c in db.TbThiSinhs
                           join d in db.TbChuyenNganhs on c.MaChuyenNganh equals d.MaChuyenNganh
                           where c.MaTS == id
                           select d).FirstOrDefault().IDNganh;
            var makhoithi = db.TbChuyenNganhs.Include(m => m.TbNganh).Where(m => m.IDNganh == IDNganh).FirstOrDefault().TbNganh.MaKhoiThi;
            ViewBag.KhoiThi = new SelectList(db.TbKhoiThis.ToList(), "MaKhoiThi", "TenKhoiThi", makhoithi);
            var TS = (from a in db.TbHeDaoTaos
                     join b in db.TbBacDaoTaos on a.MaHeDaoTao equals b.MaHeDaoTao
                     join c in db.TbThiSinh_BacDaoTaos on b.MaBacDT equals c.MaBacDT
                     where c.MaTS.Trim() == id.Trim()
                     select new { MaHeDaoTao = a.MaHeDaoTao, MaBacDT = c.MaBacDT });
            ViewBag.HeDaoTao = new SelectList(db.TbKhoiThis.ToList(), "MaKhoiThi", "TenKhoiThi", TS.FirstOrDefault().MaHeDaoTao);
            ViewBag.BacDaoTao = new SelectList(db.TbKhoiThis.ToList(), "MaKhoiThi", "TenKhoiThi", TS.FirstOrDefault().MaBacDT);
            var manganh = (from m in db.TbChuyenNganhs where (m.MaChuyenNganh == InfoCandidate.MaChuyenNganh) select m).First().IDNganh;
            ViewBag.Nganh = new SelectList(db.TbNganhs.Where(m => m.MaKhoiThi == makhoithi).ToList(), "IDNganh", "TenNganh", manganh);
            ViewBag.ChuyenNganh = new SelectList(db.TbChuyenNganhs.Where(m => m.IDNganh == manganh).ToList(), "MaChuyenNganh", "TenChuyenNganh", InfoCandidate.MaChuyenNganh);
            var matinh2 = (from c in db.TbThiSinh_Truongs
                           join d in db.TbTruongTHPTs on c.IDTruong equals d.IDTruong
                           join e in db.TbTinhs on d.MaTinh equals e.MaTinh
                           where c.MaTS == id
                           select new { Lop = c.Lop, MaTinh = d.MaTinh, IDTruong = d.IDTruong });
            ViewBag.TinhTruong10 = new SelectList(db.TbTinhs.ToList(), "MaTinh", "TenTinh", matinh2.FirstOrDefault(m => m.Lop == 10).MaTinh);
            ViewBag.TinhTruong11 = new SelectList(db.TbTinhs.ToList(), "MaTinh", "TenTinh", matinh2.FirstOrDefault(m => m.Lop == 11).MaTinh);
            ViewBag.TinhTruong12 = new SelectList(db.TbTinhs.ToList(), "MaTinh", "TenTinh", matinh2.FirstOrDefault(m => m.Lop == 12).MaTinh);
            ViewBag.TruongTHPT10 = new SelectList(db.TbTruongTHPTs.ToList(), "IDTruong", "TenTruong", matinh2.FirstOrDefault(m => m.Lop == 10).IDTruong);
            ViewBag.TruongTHPT11 = new SelectList(db.TbTruongTHPTs.ToList(), "IDTruong", "TenTruong", matinh2.FirstOrDefault(m => m.Lop == 11).IDTruong);
            ViewBag.TruongTHPT12 = new SelectList(db.TbTruongTHPTs.ToList(), "IDTruong", "TenTruong", matinh2.FirstOrDefault(m => m.Lop == 12).IDTruong);
            ViewBag.TruongDH = new SelectList(db.TbTruongDHs.ToList(), "MaTruongDH", "TenTruongDH", InfoCandidate.MaTruongDH);
            
            //ViewBag.KhuVuc = new SelectList(db.TbKhuVucs.ToList(), "MaKhuVuc", "TenKhuVuc", ThiSinh.MaKhuVuc);
            var mamon = (from c in db.TbThiSinhs
                         join d in db.TbDiemTotNghieps on c.MaTS equals d.MaTS
                         where c.MaTS == id
                         select d).FirstOrDefault();
            if (mamon != null)
            {
                ViewBag.MonTotNghiep = new SelectList(db.TbMonTotNghieps.ToList(), "MaMon", "TenMon", mamon.MaMon);
            }
            else
            {
                ViewBag.MonTotNghiep = new SelectList(db.TbMonTotNghieps.ToList(), "MaMon", "TenMon");
            }
            ViewBag.XepLoaiHS = new SelectList(db.TbXepLoaiHS.ToList(), "MaXepLoaiHS", "TenXepLoaiHS", InfoCandidate.MaXepLoaiHS);
            ViewBag.DanToc = new SelectList(db.TbDanTocs.ToList(), "MaDanToc", "TenDanToc", InfoCandidate.MaDanToc);
            ViewBag.DoiTuongUuTien = new SelectList(db.TbDoiTuongUuTiens.ToList(), "MaDoiTuong", "TenDoiTuong", InfoCandidate.MaDoiTuong);


            // Load Toán, Anh, Văn
            TbDiemTotNghiep Mark = new TbDiemTotNghiep();
            var ListMark = db.TbDiemTotNghieps.Where(m => m.MaTS == id);
            //var ListMark2 = db.TbDiemTotNghieps.Join();
            if (ListMark.Count() != 0)
            {
                foreach (var a in ListMark)
                {
                    var Subject = db.TbMonTotNghieps.FirstOrDefault(m => m.MaMon == a.MaMon).TenMon;
                    if (Subject.ToLower() == "toán")
                    {
                        ViewBag.Toan = a.Diem.ToString();
                    }
                    if (Subject.ToLower() == "tiếng anh")
                    {
                        ViewBag.Anh = a.Diem.ToString();
                    }
                    if (Subject.ToLower() == "ngữ văn")
                    {
                        ViewBag.Van = a.Diem.ToString();
                    }
                }
            }
            //var TS_HDT = db.TbThiSinh_HeDaoTaos.Where(m => m.MaTS == id).Select(m => m.MaHeDaoTao);
            //foreach (var a in TS_HDT)
            //{
            //    if (db.TbHeDaoTaos.First(m => m.MaHeDaoTao == a).TenHeDaoTao.ToLower() == "cao đẳng nghề")
            //    {
            //        ViewBag.HeCaoDang = true;
            //    }
            //    if (db.TbHeDaoTaos.First(m => m.MaHeDaoTao == a).TenHeDaoTao.ToLower() == "cao đẳng nghề")
            //    {
            //        ViewBag.HeTrungCap = true;
            //    }

            //}
            ViewBag.DaDongTien = InfoCandidate.TrangThaiDongTien;
            ViewBag.NgayHoanThanhDK = InfoCandidate.NgayHoanThanhDK.ToString();
            ViewBag.NgayDangKi = InfoCandidate.NgayDangKi.ToString();
            ViewBag.NgayDongTien = InfoCandidate.NgayDongTien.ToString();
            ViewBag.LanSuaCuoi = InfoCandidate.LanSuaCuoi.ToString();
            return View(InfoCandidate);
        }

        [HttpPost]
        public ActionResult EditRegistration(TbThiSinh item, bool LienKet = false, bool DaDongTien = false, bool HeTrungCap = false, bool HeCaoDang = false)
        {
            if (item.MaTS != null)
            {

                var InfoCandidate = db.TbThiSinhs.AsNoTracking().First(n => n.MaTS == item.MaTS);
                if (DaDongTien)
                {
                    item.TrangThaiDongTien = true;
                    item.NgayDongTien = DateTime.Now;
                    item.TrangThaiHoanThanh = true;
                    item.NgayHoanThanhDK = DateTime.Now;
                    db.TbThiSinhs.Add(item);
                }
                
                item.MaChuyenNganh = InfoCandidate.MaChuyenNganh;
                item.HinhThucDK = db.TbThiSinhs.AsNoTracking().First(m => m.MaTS == item.MaTS).HinhThucDK;
                item.TrangThaiDongTien = db.TbThiSinhs.AsNoTracking().First(m => m.MaTS == item.MaTS).TrangThaiDongTien;
                item.TrangThaiHoanThanh = db.TbThiSinhs.AsNoTracking().First(m => m.MaTS == item.MaTS).TrangThaiHoanThanh;
                item.NgayDangKi = db.TbThiSinhs.AsNoTracking().First(m => m.MaTS == item.MaTS).NgayDangKi;
                
                
                //int cansua = 0;
                var TL = (from a in db.TbBacDaoTaos
                          join b in db.TbHeDaoTaos on a.MaHeDaoTao equals b.MaHeDaoTao
                          where (b.TenHeDaoTao.ToLower().Trim() == "chính quy" || b.TenHeDaoTao.ToLower().Trim() == "liên thông") &&
                              (a.TenBacDT.ToLower().Trim() == "đại học" || a.TenBacDT.ToLower().Trim() == "cao đẳng")
                          select a.MaBacDT);
                //string TSName = db.TbThiSinh_HeDaoTaos.AsNoTracking().First(m => m.MaHeDaoTao == InfoCandidate.MaHeDaoTao).TenHeDaoTao.ToLower();
                if (TL.Count() > 0)
                {
                    // Điểm tốt nghiệp
                    TbDiemTotNghiep diem;
                    //toán văn anh
                    string[] MangMaMon = Request.Form["Subject"].Split(',');
                    string[] MangDiemMon = Request.Form["Mark"].Split(',');
                    string ten = "";
                    var listmark = db.TbDiemTotNghieps.Where(m => m.MaTS == item.MaTS);
                    if (listmark != null)
                    {
                        foreach (var a in listmark)
                        {

                            db.TbDiemTotNghieps.Remove(a);
                        }
                        SaveChanges(db);
                    }
                    for (int i = 0; i < MangMaMon.Length; i++)
                    {
                        if (MangDiemMon[i].Trim() != "")
                        {
                            ten = MangMaMon[i];
                            var mamon = db.TbMonTotNghieps.Where(m => m.TenMon == ten).FirstOrDefault().MaMon;
                            diem = new TbDiemTotNghiep { MaTS = item.MaTS, MaMon = mamon, Diem = double.Parse(MangDiemMon[i].Trim()) };
                            db.TbDiemTotNghieps.Add(diem);
                        }
                    }

                    //môn còn lại
                    if (Request.Form["Subject1"] != null && Request.Form["Mark1"] != null)
                    {
                        string[] MangMaMon2 = Request.Form["Subject1"].Split(',');
                        string[] MangDiemMon2 = Request.Form["Mark1"].Split(',');
                        for (int i = 0; i < MangMaMon2.Length; i++)
                        {
                            if (MangDiemMon2[i].Trim() != "")
                            {
                                diem = new TbDiemTotNghiep { MaTS = item.MaTS, MaMon = Int32.Parse(MangMaMon2[i]), Diem = double.Parse(MangDiemMon2[i]) };
                                db.TbDiemTotNghieps.Add(diem);
                            }
                        }
                    }

                    // Thí sinh hệ đào tạo

                    var listTS = db.TbThiSinh_BacDaoTaos.Where(m => m.MaTS == item.MaTS);
                    if (listTS != null)
                    {
                        foreach (var a in listTS)
                        {
                            db.TbThiSinh_BacDaoTaos.Remove(a);
                        }
                        db.SaveChanges();
                    }
                    if (LienKet)
                    {
                        item.LienKetQT = true;
                    }
                    if (HeCaoDang)
                    {
                        var Ma1 = (from a in db.TbBacDaoTaos
                                   join b in db.TbHeDaoTaos on a.MaHeDaoTao equals b.MaHeDaoTao
                                   where b.TenHeDaoTao.ToLower().Trim() == "nghề" && a.TenBacDT.ToLower().Trim() == "cao đẳng"
                                   select a.MaBacDT).First();
                        db.TbThiSinh_BacDaoTaos.Add(new TbThiSinh_BacDaoTao { MaBacDT = Ma1, MaTS = item.MaTS, DKThem = true, NoiDaoTao = int.Parse(Request.Form["NoiDaoTao"].Trim()), TrungTuyen = null });
                    }
                    if (HeTrungCap)
                    {
                        var Ma2 = (from a in db.TbBacDaoTaos
                                   join b in db.TbHeDaoTaos on a.MaHeDaoTao equals b.MaHeDaoTao
                                   where b.TenHeDaoTao.ToLower().Trim() == "chính quy" && a.TenBacDT.ToLower().Trim() == "trung cấp"
                                   select a.MaBacDT).First();
                        db.TbThiSinh_BacDaoTaos.Add(new TbThiSinh_BacDaoTao { MaBacDT = Ma2, MaTS = item.MaTS, DKThem = true, NoiDaoTao = int.Parse(Request.Form["NoiDaoTao"].Trim()), TrungTuyen = null });
                    }
                }
                if (item.NgayDongTien != null)
                {
                    item.NgayDongTien = item.NgayDongTien;
                }
                if (item.NgayHoanThanhDK != null)
                {
                    item.NgayHoanThanhDK = item.NgayHoanThanhDK;
                }
                //item.MaHeDaoTao = InfoCandidate.MaHeDaoTao;
                
                //item.NgayHoanThanhDK = DateTime.Now;
                item.LanSuaCuoi = DateTime.Now;
                //db.TbThiSinhs.AsNoTracking();
                var CD_HS = db.TbThiSinh_Truongs.Where(m => m.MaTS == item.MaTS);
                if (CD_HS.Count() > 0)
                {
                    foreach (var ch_hs in CD_HS)
                    {
                        db.TbThiSinh_Truongs.Remove(ch_hs);
                    }
                    SaveChanges(db);
                }
                TbThiSinh_Truong Lop10 = new TbThiSinh_Truong { MaTS = item.MaTS, IDTruong = int.Parse(Request.Form["IDTruong10"].Trim()), Lop = 10 };
                db.TbThiSinh_Truongs.Add(Lop10);
                TbThiSinh_Truong Lop11 = new TbThiSinh_Truong { MaTS = item.MaTS, IDTruong = int.Parse(Request.Form["IDTruong11"].Trim()), Lop = 11 };
                db.TbThiSinh_Truongs.Add(Lop11);
                TbThiSinh_Truong Lop12 = new TbThiSinh_Truong { MaTS = item.MaTS, IDTruong = int.Parse(Request.Form["IDTruong12"].Trim()), Lop = 12 };
                db.TbThiSinh_Truongs.Add(Lop12);
                db.Entry(item).State = EntityState.Modified;
                db.SaveChanges();
            }

            return RedirectToAction("CandidateList", "CandidateManagement");
        }
        #endregion
        #endregion

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}